//
//  LSAddCollectionViewController.m
//  LibraryStorm
//
//  Created by Enel@Lightning on 4/7/14.
//  Copyright (c) 2014 3ATeam. All rights reserved.
//

#import "LSAddCollectionViewController.h"
#import "BookCollection.h"
#import "BookDetail.h"
#import "LSCoreDataController.h"
#import "LSArrayDataSource.h"
#import "LSAddCollectionCell.h"
#import "LSAddCollectionCell+ConfigureForBook.h"
#import "UIColor+HexString.h"

#define SearchBar_Height 44.0f

static NSString * const AddCollectionCellIdentifier = @"AddCollectionCellId";
@interface LSAddCollectionViewController () <UITableViewDelegate, UISearchBarDelegate>

@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (strong, nonatomic) BookCollection *collection;
@property (strong, nonatomic) NSArray *books;
@property (strong, nonatomic) NSMutableSet *bookIds;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) LSArrayDataSource *booksArrayDataSource;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topLayoutSearchBar;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topLayoutTableView;
@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;

@end

@implementation LSAddCollectionViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationController.navigationBar setTranslucent:NO];
    [self.view setBackgroundColor:[UIColor colorWithHexString:Color_Orange_View]];

    [self setListBarItem:@[@(BarItemButton_Done)]];
    // Do any additional setup after loading the view.
    self.managedObjectContext = [[LSCoreDataController sharedInstance] newManagedObjectContext];
    self.collection = (BookCollection *)[self.managedObjectContext objectWithID:self.managedObjectId];
    self.bookIds = [NSMutableSet setWithArray:self.collection.bookIds];
    [self setTitle:self.collection.name];

    _tableView.contentInset = UIEdgeInsetsMake(SearchBar_Height, 0, 0, 0);
    [_tableView setBackgroundColor:[UIColor whiteColor]];

    [self loadRecordsFromCoreData];
    [self setupTableView];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self registerForKeyboardNotifications];
}

- (void)viewWillDisappear:(BOOL)animated {
    if (SD_IS_IOS7) {
        [self.navigationController.navigationBar setTranslucent:YES];
    }
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super viewWillDisappear:animated];
}

- (void)setupTableView
{
    TableViewCellConfigureBlock configureCell = ^(LSAddCollectionCell *cell, BookDetail *book) {
        [cell configureForBook:book];
        cell.selectedIconImageView.image = ICON_NONSELECTED;
        for (NSNumber *bookId in self.bookIds.allObjects) {
            if (bookId.intValue == book.bookId.intValue) {
                cell.selectedIconImageView.image = ICON_SELECTED;
            }
        }
    };
    
    self.booksArrayDataSource = [[LSArrayDataSource alloc] initWithItems:self.books
                                                          cellIdentifier:AddCollectionCellIdentifier
                                                      configureCellBlock:configureCell];
    self.tableView.dataSource = self.booksArrayDataSource;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 87;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (indexPath.row < self.books.count) {
        BookDetail *book = [self.books objectAtIndex:indexPath.row];
        int bookId = book.bookId.intValue;
        LSAddCollectionCell *cell = (LSAddCollectionCell *)[tableView cellForRowAtIndexPath:indexPath];
        NSSet *tempBookIds = [NSSet setWithSet:self.bookIds];
        for (NSNumber *aBookId in tempBookIds.allObjects) {
            if (aBookId.intValue == bookId) {
                [self.bookIds removeObject:aBookId];
                cell.selectedIconImageView.image = ICON_NONSELECTED;
                return;
            }
        }
        
        [self.bookIds addObject:book.bookId];
        cell.selectedIconImageView.image = ICON_SELECTED;
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.navigationController.isNavigationBarHidden) {
        return;
    }
    else {
        if (scrollView.contentOffset.y < -SearchBar_Height) {
            if (_topLayoutSearchBar.constant == 0) {
                return;
            }
            else {
                _topLayoutSearchBar.constant = 0;
            }
        }
        else {
            if (scrollView.contentOffset.y > 0) {
                if (_topLayoutSearchBar.constant == -SearchBar_Height) {
                    return;
                }
                else {
                    _topLayoutSearchBar.constant = -SearchBar_Height;
                }
            }
            else {
                _topLayoutSearchBar.constant = -scrollView.contentOffset.y-SearchBar_Height;
            }
        }
    }
}

#pragma mark - Load Records
- (void)loadRecordsFromCoreData
{
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"bookId" ascending:YES];
    self.books = [BookDetail getAllObjectsInContext:self.managedObjectContext withSortDescriptor:sortDescriptor resetContext:NO fetchLimit:0];
}

#pragma mark - Target Action
/**
 * Method name: clickDoneButton
 * Description: Save books which add on collection to core data.
 * Parameters: sender
 */
- (void)clickDoneButton:(id)sender
{
    [self.collection setObjectInContext:self.managedObjectContext withValue:self.bookIds.allObjects forKey:@"bookIds"];
    /*Add book to collection relationship*/
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"bookId IN %@", self.bookIds.allObjects];
    NSArray *books = [BookDetail getAllObjectsInContext:self.managedObjectContext withSortDescriptor:nil withPredicate:predicate resetContext:NO fetchLimit:0];
    for (BookDetail *book in books) {
        [self.collection addListOfBooksObject:book];
    }
    
    [self.managedObjectContext performBlockAndWait:^{
        NSError *error = nil;
        BOOL saved = [self.managedObjectContext save:&error];
        if (!saved) {
            NSLog(@"Unable to save context after deleting records for class Collection because %@", error);
        }
        [[LSCoreDataController sharedInstance] saveMasterContext];
    }];
    
    self.selectBooksCompletionBlock();
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [_searchBar setShowsCancelButton:YES animated:YES];

    if (SD_IS_IOS7) {
        _topLayoutTableView.constant = STATUSBAR_HEIGHT;
        _topLayoutSearchBar.constant = _topLayoutTableView.constant;
    }
    
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [_searchBar setShowsCancelButton:NO animated:YES];

    _topLayoutTableView.constant = 0.0f;
    _topLayoutSearchBar.constant = 0.0f;
    
    return YES;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    if ([searchBar isFirstResponder]) {
        [searchBar resignFirstResponder];
    }
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    if ([searchBar isFirstResponder]) {
        [searchBar resignFirstResponder];
    }
}

#pragma mark - Scroll View
// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    if (Device_Orientation == UIInterfaceOrientationPortrait) {
        [_tableView setContentInset:UIEdgeInsetsMake(SearchBar_Height, 0, kbSize.height, 0)];
    }else {
        [_tableView setContentInset:UIEdgeInsetsMake(SearchBar_Height, 0, kbSize.width, 0)];
    }
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    [_tableView setContentInset:UIEdgeInsetsMake(SearchBar_Height, 0, 0, 0)];
    [_tableView scrollRectToVisible:CGRectMake(0, 0, _tableView.bounds.size.width, 87.0f) animated:YES];
}
@end
